//
//  ViewController.m
//  UI19-JSON（网易新闻练习）
//
//  Created by 韩旭 on 16/8/9.
//  Copyright © 2016年 lanou. All rights reserved.
//
#import "ViewController.h"
#import "NewsTiltleModel.h"
#import "HX_CollectionViewCell.h"
#import "HX_CollectionLayout.h"
@interface ViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, HX_CollectionLayoutDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *MyCollectionVIew;
@property (nonatomic, strong) NSMutableArray<NewsTiltleModel *> *arrDataSource;
@end
@implementation ViewController
- (NSMutableArray *)arrDataSource {
    if (!_arrDataSource) {
        _arrDataSource = [NSMutableArray array];
    }
    return _arrDataSource;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"newsJSON" ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSError *error = nil;
    NSDictionary *dicJson = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
    NSArray *arrList = dicJson[@"tList"];
    for (NSDictionary *dic in arrList) {
        [self.arrDataSource addObject:[NewsTiltleModel newsTitleDic:dic]];
    }
    HX_CollectionLayout *layout = (HX_CollectionLayout *)self.MyCollectionVIew.collectionViewLayout;
    layout.delegate = self;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout width:(CGFloat)width sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSString *string = [_arrDataSource[indexPath.row] tname];
    CGRect new = [string boundingRectWithSize:CGSizeMake(MAXFLOAT, CGRectGetHeight(self.MyCollectionVIew.bounds)) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:17]} context:nil];
    return ceill(CGRectGetWidth(new));
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _arrDataSource.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HX_CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.model = _arrDataSource[indexPath.row];
    return cell;
}
@end
